<?php

namespace GatewayChat\controller;
use GatewayChat\Contract\OnMessageInterface;
use GatewayChat\Contract\OnWebSocketConnectInterface;
use GatewayChat\Contract\OnWorkerInterface;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Lib\Gateway;
use Workerman\Lib\Timer;
use Workerman\MySQL\Connection;

class Debug implements OnWebSocketConnectInterface,OnWorkerInterface,OnMessageInterface
{

    public function  onWorkerStart(BusinessWorker $worker)
    {
        // 注册一个定时器，用于向admin用户组发送所在线用户数据
        //为什么要用2层定时器包住呢，主要定时器直接运行,没有任何用户连接，没法取得所用用户信息 50秒后才检测用户
        if($worker->id===1){
            Timer::add(10,function (){
                Timer::add(50,function (){
                    $on_line=Gateway::getAllClientIdList();
                    $on_line=array_values($on_line);
                    Gateway::sendToGroup('admin',json_encode(['method'=>'allUser','data'=>$on_line],true));
                });
            },null,false);
        }

    }

    public function onWorkerStop(BusinessWorker $worker)
    {
        // TODO: Implement onWorkerStop() method.
    }
    public function onConnect(string $client_id)
    {
        // TODO: Implement onWorkerStop() method.
    }

    public function onWebSocketConnect($client_id, $data, Connection $db, \Redis $redis)
    {
        Gateway::joinGroup($client_id,'admin');
    }
    public function onMessage($client_id, $message, Connection $db, \Redis $redis)
    {
        if($message==='ping')
            return false;
        Gateway::sendToGroup('admin',$message);
    }
}